#pragma once

#ifndef M_ESP_NOW_HPP
#define M_ESP_NOW_HPP

#include <Arduino.h>

#ifdef ESP32
#include <WiFi.h>
#include <esp_now.h>
#else
#include <ESP8266WiFi.h>
#include <espnow.h>
#endif

// 此处将地址设置为{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} 则向所有开发板发送
uint8_t broadcastAddress_all[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

String inline getMacNumber()
{
    String mac = WiFi.macAddress();
    mac.replace(":", ", 0x");
    mac = "uint8_t broadcastAddress[] = {0x" + mac + "}";
    return mac;
}

// Peer info
esp_now_peer_info_t peerInfo;

// 发送时的回调函数，用于验证是否发送成功
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status)
{
    Serial.print("\r\nLast Packet Send Status:\t");
    Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}

void espBegin()
{

    // Set ESP32 as a Wi-Fi Station
    WiFi.mode(WIFI_STA);

    // Initilize ESP-NOW
    if (esp_now_init() != ESP_OK)
    {
        Serial.println("Error initializing ESP-NOW");
        return;
    }

    // Register the send callback
    esp_now_register_send_cb(OnDataSent);

    // register peer
    peerInfo.channel = 0;
    peerInfo.encrypt = false;

    // register all peer
    memcpy(peerInfo.peer_addr, broadcastAddress_all, 6);
    if (esp_now_add_peer(&peerInfo) != ESP_OK)
    {
        Serial.println("Failed to add peer");
        return;
    }

    // register first peer
    // memcpy(peerInfo.peer_addr, broadcastAddress1, 6);
    // if (esp_now_add_peer(&peerInfo) != ESP_OK)
    // {
    //     Serial.println("Failed to add peer");
    //     return;
    // }

    // // register second peer
    // memcpy(peerInfo.peer_addr, broadcastAddress2, 6);
    // if (esp_now_add_peer(&peerInfo) != ESP_OK)
    // {
    //     Serial.println("Failed to add peer");
    //     return;
    // }
}

void espSend(const uint8_t *data_struct, const uint8_t *peer_addr)
{
    // 若需向所有的开发板发送，则peer_addr为0
    esp_err_t result = esp_now_send(peer_addr, data_struct, sizeof(data_struct));

    if (result == ESP_OK)
    {
        Serial.println("Sending confirmed");
    }
    else
    {
        Serial.println("Sending error");
    }
}

#endif
